package com.njuaplusplus.www.activity;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.njuaplusplus.www.R;
import com.njuaplusplus.www.db.MyDatabaseHelper;
import com.njuaplusplus.www.utils.Sudoku;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class TestSudokuActivity extends Activity {
	/** Called when the activity is first created. */

	MyDatabaseHelper mDbHelper;
	private Sudoku mSudoku = null;
	private GridView mGridView;
	private String[] numberItems;
	private int[] sudokuArray = new int[81];
	private Button mButton_generateSudoku;
	private Button mBuuton_solveSudoku;
	private Button mButton_save;
	private Button mButton_load;
	private TextView mTextView_score;
	private EditText mEditText_space;
	private int score = 0;
	private List<Map<String, Object>> listItems = new ArrayList<Map<String, Object>>();
	private int compID = 1;
	private boolean[] holes = new boolean[81];

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sudoku_layout);

		mDbHelper = new MyDatabaseHelper(this, "mSudokuComp.db3", 1);
		mGridView = (GridView) findViewById(R.id.gridView_sudoku);
		numberItems = getResources().getStringArray(R.array.numberItems);
		Arrays.fill(sudokuArray, -1);
		mButton_generateSudoku = (Button)findViewById(R.id.button_generateSudoku);
		mBuuton_solveSudoku = (Button)findViewById(R.id.button_solveSudoku);
		mButton_save = (Button)findViewById(R.id.button_save);
		mButton_load = (Button)findViewById(R.id.button_load);
		mTextView_score = (TextView)findViewById(R.id.textView_score);
		
		mEditText_space = (EditText)findViewById(R.id.editText_space);
		
		mTextView_score.setText(score+"");
		
		mButton_generateSudoku.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				System.out.println("Generate space == " + mEditText_space.getText() + "  " + mEditText_space.toString());
				int space = Integer.parseInt(mEditText_space.getText().toString());
				System.out.println("space == " + space);
				
				mSudoku = new Sudoku();
				holes = mSudoku.getHoles();
				sudokuArray = mSudoku.generateSudoku(space);
				setGridView();
			}
		});
		
		mBuuton_solveSudoku.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				solveSudoku();
			}
		});
		
		mGridView.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View view, final int position,
					long id) {
				// TODO Auto-generated method stub
				System.out.println("parent == " + parent);
				System.out.println("view == " + view);
				System.out.println("postion == " + position);
				System.out.println("id == " + id + " == " + parent.getItemIdAtPosition(position));
				System.out.println("data == " + parent.getItemAtPosition(position));
//				((TextView)view.findViewById(R.id.textView_cell)).setBackgroundColor(Color.BLUE);

				if (mSudoku.isHoles(position)) {

					new AlertDialog.Builder(TestSudokuActivity.this)
					.setTitle("Pick a number")
					.setItems(numberItems, new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							int tempNumber = sudokuArray[position];
							sudokuArray[position] = Integer.parseInt(numberItems[which]); 
							if (mSudoku.isCorrect(position, sudokuArray)) {
								Map<String, Object> map = new HashMap<String, Object>();
								map.put("NUMBER", numberItems[which]);
								listItems.set(position, map);
								refreshGridView();
								if (validateSudoku()) {
									score += 10;
									mTextView_score.setText(score+"");
									Toast.makeText(getApplicationContext(), "Congratulations!", Toast.LENGTH_LONG).show();
								}
							}
							else {
								sudokuArray[position] = tempNumber;
								Toast.makeText(getApplicationContext(), "The number is wrong!", Toast.LENGTH_SHORT).show();
							}
						}
					})
					.show();
				}
			}

		});
		
		mButton_save.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				saveSudoku(mDbHelper.getReadableDatabase(), sudokuArray, holes, score+"");
			}
		});
		
		mButton_load.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				loadSudoku();
				listItems.clear();
				for (int i=0; i<sudokuArray.length; i++) {
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("NUMBER", (sudokuArray[i]==-1 ? " " : sudokuArray[i]));
					listItems.add(map);
				}

				refreshGridView();
				mTextView_score.setText(score+"");
			}
		});
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();

		for (int i=0; i<sudokuArray.length; i++) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("NUMBER", (sudokuArray[i]==-1 ? " " : sudokuArray[i]));
			listItems.add(map);
		}

		refreshGridView();

	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		
		if (mDbHelper != null) {
			mDbHelper.close();
		}
	}

	private void refreshGridView() {
		mGridView.setAdapter(new SimpleAdapter(TestSudokuActivity.this, listItems, R.layout.cell, new String[] {"NUMBER"}, new int[] {R.id.textView_cell}));
	}
	
	private void setGridView() {
		listItems.clear();
		for (int i=0; i<sudokuArray.length; i++) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("NUMBER", (sudokuArray[i]==-1 ? " " : sudokuArray[i]));
			listItems.add(map);
		}
		refreshGridView();
	}
	
	private boolean validateSudoku() {
		for (int i : sudokuArray) {
			if (i < 0) {
				return false;
			}
		}
		
		return true;
	}
	
	private void solveSudoku() {
		mSudoku = new Sudoku();
		mSudoku.initSudokuMatrix(sudokuArray);
		mSudoku.solveSudoku();
		ArrayList<int[]> resultList = mSudoku.getResultList();
		if (resultList != null && resultList.size() > 0) {
			sudokuArray = resultList.get(0);
			setGridView();
		}
		else {
			Toast.makeText(getApplicationContext(), "No solution", Toast.LENGTH_SHORT).show();
		}
		
	}
	
	private void saveSudoku(SQLiteDatabase db, int[] s, boolean[] h, String sc) {
		String strtmp = "";
		for (int i=0; i<s.length; i++) {
			strtmp = strtmp + s[i] + ".";
			if (h[i]) {
				strtmp += "1"; 
			}
			else {
				strtmp += "0";
			}
			strtmp += ";";
		}
		db.delete("sudokucomp", "compID=?", new String[] {compID+""});
		db.execSQL("insert into sudokucomp values(?, ?, ?)", new String[] {compID+"", strtmp, sc});
	}

	private void loadSudoku() {
		Cursor mCursor = mDbHelper.getReadableDatabase().rawQuery(
				"select * from sudokucomp where compID=?", new String[] {compID+""});
		while (mCursor.moveToNext()) {
			String strtmp = mCursor.getString(1);
			score = mCursor.getInt(2);
			String[] str1 = strtmp.split(";");
			for (int i=0; i<str1.length; i++) {
				String str2 = str1[i];
				String[] str3 = str2.split("\\.");
				sudokuArray[i] = Integer.parseInt(str3[0]);
				if (str3[1].equals(0)) {
					holes[i] = false;
				}
				else {
					holes[i] = true;
				}
			}
		}
		
	}





}